/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nc.kyiv.yellow.sociallibrary.ConnectionManager;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Locale;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 *
 * @author My
 */
public class ConnectionManager {

    //private static ConnectionManager instance;
    private static DataSource connectionPool;

    private ConnectionManager() {
    }

    static {
        try {
            System.out.println("Creating connectionPool instance!");
            Context ic = new InitialContext();
            Locale.setDefault(Locale.ENGLISH);
            connectionPool = (DataSource) ic.lookup("jdbc/sociallibraryConnection");
        } catch (NamingException ex) {
            System.out.println("Lookup failed. Error: " + ex.getMessage());
        }
    }

    public static Connection getConnection() {
        try {
            Connection conn = connectionPool.getConnection();
            //conn.setAutoCommit(false);
            return conn;

        } catch (SQLException ex) {
            System.out.println("Can't obtain connection from connection pool. Error: " + ex);
            return null;
        }
    }

    public static void releaseConnection(Connection connection) {
        try {
            connection.close();
        } catch (SQLException ex) {
            System.out.println("Can't release connection. Error: " + ex);
        }
    }
}
